import java.util.Stack;

/**
 * 项目名称：wangxu
 * 类 名 称：BM83
 * 描 述：字符串变形
 * 创建时间：2023/2/27 10:22 上午
 * 创 建 人：wang-xu
 */
public class BM83 {
    public static void main(String[] args) {
        System.out.println(trans("This is a sample",16));
    }
    public static String trans(String s, int n) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c >= 'a' && c <= 'z') {
                sb.append(String.valueOf(c).toUpperCase());
            }
            if (c >= 'A' && c <= 'Z') {
                sb.append(String.valueOf(c).toLowerCase());
            }
            if (c == ' ') {
                sb.append(c);
            }
        }
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < sb.toString().split(" ").length; i++) {
            stack.push(sb.toString().split(" ")[i]);
        }
        // 如果末位字符为空格，也需要入栈
        if (s.charAt(n-1)==' '){
            stack.push(" ");
        }
        StringBuilder nb = new StringBuilder();
        int num = stack.size();
        for (int i = 0; i < num; i++) {
            if (stack.peek() == " "){
                nb.append(stack.peek());
                stack.pop();
                continue;
            }
            nb.append(stack.peek());
            if (nb.length() < n) {
                nb.append(" ");
            }
            stack.pop();
        }
        return nb.toString();
    }
}
